package com.taorenqi.business.fragment.login;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taorenqi.business.R;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.utils.ValidatorUtils;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.business.widget.verifycode.Rotate;
import com.taorenqi.data.cache.ACache;
import com.taorenqi.data.cache.EnumKey;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.login.CodeDataEntity;
import com.taorenqi.data.requestmsgtoken.RegisterDataHttpRequest;
import com.taorenqi.data.service.LoginDataHttpRequest;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 找回密码
 * A simple {@link Fragment} subclass.
 */
public class FindbackPwdFragment extends BaseBackFragment {


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.et_forgetPw_phone)
    EditText etForgetPwPhone;
    @Bind(R.id.et_forgetPw_pw)
    EditText etForgetPwPw;
    @Bind(R.id.et_forgetPw_pw_again)
    EditText etForgetPwPwAgain;
    @Bind(R.id.et_forgetPw_tuxing)
    EditText etForgetPwTuxing;
    @Bind(R.id.tuxingyanz)
    ImageView tuxingyanz;
    @Bind(R.id.et_forgetPw_yzm)
    EditText etForgetPwYzm;
    @Bind(R.id.tv_forget_yzm)
    TextView tvForgetYzm;
    @Bind(R.id.ll_forgetPw_next)
    LinearLayout llForgetPwNext;
    @Bind(R.id.activity_forget_pw)
    LinearLayout activityForgetPw;

    private BasePageableResponse<CodeDataEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriberCode;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriber;

    private String token;//发送短信返回的token
    private int time = 60;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (time == 0) {
                        time = 60;
                        if (tvForgetYzm != null) {
                            tvForgetYzm.setClickable(true);
                            tvForgetYzm.setText("获取验证码");
                        }
                    } else {
                        if (tvForgetYzm != null) {
                            tvForgetYzm.setText("重新获取(" + (--time) + ")");
                            handler.sendEmptyMessageDelayed(100, 1000);
                        }
                    }
                    break;
            }
        }
    };

    public static FindbackPwdFragment newInstance() {
        // Required empty public constructor
        FindbackPwdFragment fragment = new FindbackPwdFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_findback_pwd, container, false);
        ButterKnife.bind(this, view);
        initToolbar();
        initView();
        initRequest();
        return attachToSwipeBack(view);
    }

    private void initRequest() {

        //验证码
        subscriberCode = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {

            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                data = entity;
                ToastUtil.showToast(_mActivity,"验证码发送成功");
                token = data.getToken();
                ACache.get(_mActivity).put(EnumKey.User.MSG_TOKEN,token);
            }
        };

        //找回密码
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {
            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                //接口请求成功后处理
                ToastUtil.showToast(_mActivity,"密码修改成功");
                start(ModifySuccessfullyFragment.newInstance());
            }
        };
    }
    private void initToolbar() {
        toolbar.setTitle("找回密码");
        initToolbarNav(toolbar);
    }

    private void initView() {
        tuxingyanz.setImageBitmap(Rotate.getInstance().createBitmap());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tuxingyanz, R.id.tv_forget_yzm, R.id.ll_forgetPw_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tuxingyanz://图形验证码
                initView();
                break;
            case R.id.tv_forget_yzm://获取验证码
                sendMsgCode();
                break;
            case R.id.ll_forgetPw_next://确认
                submit();
                break;
        }
    }

    private void submit() {
        String mobile = etForgetPwPhone.getText().toString().trim();//手机号
        String tuxing = etForgetPwTuxing.getText().toString().trim();//图形验证码
        String vcode = etForgetPwYzm.getText().toString().trim();//验证码
        String password = etForgetPwPw.getText().toString().trim();//密码
        String password_again = etForgetPwPwAgain.getText().toString().trim();//密码 再次
        Map<String,String> map = new HashMap<>();
        map.put("mobile",mobile);
        map.put("password",password);
        map.put("vcode",vcode);
        String sign = Encoder.getSigns(map);

        if (TextUtils.isEmpty(mobile)||mobile.length()<11) {
            ToastUtil.showToast(_mActivity,"请输入正确手机号码");
            return;
        }

        if (!ValidatorUtils.isMobile(mobile)) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
            return;
        }

        if (TextUtils.isEmpty(password)||password.length()<6) {
            ToastUtil.showToast(_mActivity,"请按要求输入密码");
            return;
        }

        if (!password.equals(password_again)){
            ToastUtil.showToast(_mActivity,"两次密码不一致");
            return;
        }


        if(!Rotate.getInstance().getCode().toUpperCase().equals(tuxing.toUpperCase())){
            ToastUtil.showToast(_mActivity,"图形验证码错误");
            return;
        }

        if (TextUtils.isEmpty(vcode)) {
            ToastUtil.showToast(_mActivity,"请按要求输入验证码");
            return;
        }

        if (TextUtils.isEmpty(token)) {
            ToastUtil.showToast(_mActivity,"请发送验证短信");
            return;
        }

        RegisterDataHttpRequest.getInstance(MyApp.getApp()).postModifyPwd(new ProgressSubscriber(subscriber,_mActivity),
                mobile,password,vcode,sign);
    }

    private void sendMsgCode() {
        String mobile = etForgetPwPhone.getText().toString().trim();//手机号
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
        }
        if (!ValidatorUtils.isMobile(mobile)) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
        } else {
            //发送验证码请求
            int reg = 0;
            Map<String,String> map = new HashMap<>();
            map.put("mobile",mobile);
            map.put("reg",reg+"");
            String sign = Encoder.getSigns(map);

            LoginDataHttpRequest.getInstance(MyApp.getApp()).postSendSms(
                    new ProgressSubscriber(subscriberCode,_mActivity),mobile,reg,sign);
            tvForgetYzm.setText("重新获取(" + time + ")");
            tvForgetYzm.setClickable(false);
            handler.sendEmptyMessageDelayed(100, 1000);
        }
    }
}
